<template>
	<div>
		<van-form >
			<van-field v-model="username" name="账号" label="账号" placeholder="账号"
				:rules="[{ required: true, message: '请填写用户名' }]" />
			<van-field v-model="password" type="password" name="密码" label="密码" right-icon="warning-o" placeholder="密码"
				:rules="[{ required: true, message: '请填写密码' }]" />
			<div style="margin: 16px;">
				<van-button color='#F688A4' round block type="info" @click='register()'>登录</van-button>
			</div>
			<div class="felx">
				<span @click="login()">注册</span>
				<span>忘记密码</span>
			</div>
		</van-form>
	</div>
</template>

<script>
	import {
		Form,
		Field,
		Toast
	} from 'vant';
	import API from '../utils/API.js'
	export default {
		data() {
			return {

				cut: true,
				username: '',
				password: '',
				tel: '',
				sms: '',
				errmsg: ''
			};
		},
		components: {
			[Form.name]: Form,
			[Field.name]: Field,
		},
		methods: {
			register() { // 登录
				let use = { //获取用户输入数据 封装给后端
					username: this.username,
					password: this.password,
				}
				// console.log('submit', use)
				this.$post(API.POST_AUTH_LOGIN, use)
					.then(res => {
						// 返回错误码不为0 登录失败
						if (res.data.errno != 0) {
							this.username = ''
							this.password = ''
							Toast(res.data.errmsg);
						} else if(res.data.errmsg == "成功") {
							// 登录成功 保存信息并跳转回个人信息页面
							// console.log(res.data.data.token)
							this.setStorage(res.data.data)
							
							const userInfo = {
								nickName: res.data.data.userInfo.nickname,
								avatarUrl: res.data.data.userInfo.avatar,
								token: res.data.data.token
							}
							//异步存储给vuex
							this.$store.dispatch('login', userInfo)
							//页面跳转 到主页
							this.$router.push({
								path: "/my"
							})
						}
						console.log(res.data)
						// console.log(res)
					
				
					})

			},
			setStorage(data) {
				// console.log(data)
				localStorage.setItem('token', data.token)
				localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
			},
			login() {
					this.$router.push({
						path: "/register"
					})
			},
			
		},
	};
</script>

<style>
	.felx {
		display: flex;
		justify-content: space-between;
		width: 96%;
		font-size: 18px;
		margin: 10px;

	}
</style>
